package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("CrawlerfilestandardService")
@Transactional

public class CrawlerfilestandardServiceImpl extends CmiEmaService implements CrawlerfilestandardService {
	public CrawlerfilestandardServiceImpl() {
	}

	@Transactional
	public Crawlerfilestandard saveCrawlerfilestandard(Crawlerfilestandard crawlerfilestandard) {
		Set<Crawlerfile> existingCrawlerfilesForCrawlerfilestandard = new HashSet<Crawlerfile>();
		Set<Crawlerfilestandardetail> existingCrawlerfilestandardetailsForCrawlerfilestandard = new HashSet<Crawlerfilestandardetail>();

		Set<Crawlerfile> selectedCrawlerfilesForCrawlerfilestandard = crawlerfilestandard
				.getCrawlerfilesForCrawlerfilestandard();
		Set<Crawlerfilestandardetail> selectedCrawlerfilestandardetailsForCrawlerfilestandard = crawlerfilestandard
				.getCrawlerfilestandardetailsForCrawlerfilestandard();

		if (crawlerfilestandard.getId() == null) {

			Crawlerfilestandard existingCrawlerfilestandard = crawlerfilestandardDAO
					.findCrawlerfilestandardByPhysicalPrimaryKey(crawlerfilestandard.getName());

			if (isEquals(crawlerfilestandard, existingCrawlerfilestandard)) {
				return existingCrawlerfilestandard;
			}

			crawlerfilestandard = crawlerfilestandardDAO.store(crawlerfilestandard);
			crawlerfilestandardDAO.flush();

			for (Crawlerfile relatedCrawlerfile : selectedCrawlerfilesForCrawlerfilestandard) {
				relatedCrawlerfile.setCrawlerfilestandard(crawlerfilestandard);
				crawlerfileDAO.store(relatedCrawlerfile);
			}
			for (Crawlerfilestandardetail relatedCrawlerfilestandardetail : selectedCrawlerfilestandardetailsForCrawlerfilestandard) {
				relatedCrawlerfilestandardetail.setCrawlerfilestandard(crawlerfilestandard);
				crawlerfilestandardetailDAO.store(relatedCrawlerfilestandardetail);
			}
		} else {
			Crawlerfilestandard existingCrawlerfilestandard = crawlerfilestandardDAO
					.findCrawlerfilestandardByPrimaryKey(crawlerfilestandard.getId());

			existingCrawlerfilesForCrawlerfilestandard = existingCrawlerfilestandard
					.getCrawlerfilesForCrawlerfilestandard();
			existingCrawlerfilestandardetailsForCrawlerfilestandard = existingCrawlerfilestandard
					.getCrawlerfilestandardetailsForCrawlerfilestandard();

			Set<Crawlerfile> prepareDeleteCrawlerfilesForCrawlerfilestandard = new HashSet<Crawlerfile>();
			Set<Crawlerfile> prepareAddCrawlerfilesForCrawlerfilestandard = new HashSet<Crawlerfile>();

			prepareDeleteCrawlerfilesForCrawlerfilestandard.addAll(selectedCrawlerfilesForCrawlerfilestandard);
			prepareDeleteCrawlerfilesForCrawlerfilestandard.addAll(existingCrawlerfilesForCrawlerfilestandard);

			prepareAddCrawlerfilesForCrawlerfilestandard.addAll(selectedCrawlerfilesForCrawlerfilestandard);
			prepareAddCrawlerfilesForCrawlerfilestandard.addAll(existingCrawlerfilesForCrawlerfilestandard);

			prepareDeleteCrawlerfilesForCrawlerfilestandard.removeAll(selectedCrawlerfilesForCrawlerfilestandard);
			prepareAddCrawlerfilesForCrawlerfilestandard.removeAll(existingCrawlerfilesForCrawlerfilestandard);

			for (Crawlerfile relatedCrawlerfile : prepareAddCrawlerfilesForCrawlerfilestandard) {
				relatedCrawlerfile.setCrawlerfilestandard(crawlerfilestandard);
				crawlerfileDAO.store(relatedCrawlerfile);
			}

			for (Crawlerfile relatedCrawlerfile : prepareDeleteCrawlerfilesForCrawlerfilestandard) {
				relatedCrawlerfile.setCrawlerfilestandard(null);
				crawlerfileDAO.store(relatedCrawlerfile);
			}
			Set<Crawlerfilestandardetail> prepareDeleteCrawlerfilestandardetailsForCrawlerfilestandard = new HashSet<Crawlerfilestandardetail>();
			Set<Crawlerfilestandardetail> prepareAddCrawlerfilestandardetailsForCrawlerfilestandard = new HashSet<Crawlerfilestandardetail>();

			prepareDeleteCrawlerfilestandardetailsForCrawlerfilestandard
					.addAll(selectedCrawlerfilestandardetailsForCrawlerfilestandard);
			prepareDeleteCrawlerfilestandardetailsForCrawlerfilestandard
					.addAll(existingCrawlerfilestandardetailsForCrawlerfilestandard);

			prepareAddCrawlerfilestandardetailsForCrawlerfilestandard
					.addAll(selectedCrawlerfilestandardetailsForCrawlerfilestandard);
			prepareAddCrawlerfilestandardetailsForCrawlerfilestandard
					.addAll(existingCrawlerfilestandardetailsForCrawlerfilestandard);

			prepareDeleteCrawlerfilestandardetailsForCrawlerfilestandard
					.removeAll(selectedCrawlerfilestandardetailsForCrawlerfilestandard);
			prepareAddCrawlerfilestandardetailsForCrawlerfilestandard
					.removeAll(existingCrawlerfilestandardetailsForCrawlerfilestandard);

			for (Crawlerfilestandardetail relatedCrawlerfilestandardetail : prepareAddCrawlerfilestandardetailsForCrawlerfilestandard) {
				relatedCrawlerfilestandardetail.setCrawlerfilestandard(crawlerfilestandard);
				crawlerfilestandardetailDAO.store(relatedCrawlerfilestandardetail);
			}

			for (Crawlerfilestandardetail relatedCrawlerfilestandardetail : prepareDeleteCrawlerfilestandardetailsForCrawlerfilestandard) {
				relatedCrawlerfilestandardetail.setCrawlerfilestandard(null);
				crawlerfilestandardetailDAO.store(relatedCrawlerfilestandardetail);
			}
			crawlerfilestandard = crawlerfilestandardDAO.store(crawlerfilestandard);
			crawlerfilestandardDAO.flush();
		}

		crawlerfileDAO.flush();
		crawlerfilestandardetailDAO.flush();
		return crawlerfilestandard;
	}

	public void deleteCrawlerfilestandard(Crawlerfilestandard crawlerfilestandard) {
		crawlerfilestandardDAO.remove(crawlerfilestandard);
		crawlerfilestandardDAO.flush();
	}

	@Transactional
	public void deleteCrawlerfilestandards(Set<Integer> deleteCrawlerfilestandardsId) {
		Query query = crawlerfilestandardDAO.createNamedQuery("deleteCrawlerfilestandardsById", -1, -1);
		query.setParameter(1, deleteCrawlerfilestandardsId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Crawlerfilestandard> loadCrawlerfilestandards() {
		return crawlerfilestandardDAO.findAllCrawlerfilestandards();

	}

	@Transactional
	public Set<Crawlerfilestandard> loadReferenceCrawlerfilestandards(Set<Crawlerfilestandard> crawlerfilestandards) {
		Iterator<Crawlerfilestandard> crawlerfilestandardsIterator = crawlerfilestandards.iterator();
		Set<Crawlerfilestandard> referencedCrawlerfilestandards = new HashSet<>();
		while (crawlerfilestandardsIterator.hasNext()) {
			Crawlerfilestandard currentCrawlerfilestandard = crawlerfilestandardsIterator.next();

			if (!currentCrawlerfilestandard.getCrawlerfilesForCrawlerfilestandard().isEmpty()) {
				referencedCrawlerfilestandards.add(currentCrawlerfilestandard);
				continue;
			}

			if (!currentCrawlerfilestandard.getCrawlerfilestandardetailsForCrawlerfilestandard().isEmpty()) {
				referencedCrawlerfilestandards.add(currentCrawlerfilestandard);
				continue;
			}
		}
		return referencedCrawlerfilestandards;
	}

	public Set<Crawlerfilestandard> loadCrawlerfilestandardsByIdSet(Set<Integer> crawlerfilestandardIdSet) {

		Iterator<Integer> crawlerfilestandardIdIterator = crawlerfilestandardIdSet.iterator();
		Set<Crawlerfilestandard> crawlerfilestandardSet = new HashSet<>();
		while (crawlerfilestandardIdIterator.hasNext()) {
			Integer id = crawlerfilestandardIdIterator.next();
			Crawlerfilestandard currentCrawlerfilestandard = crawlerfilestandardDAO.findCrawlerfilestandardById(id);
			crawlerfilestandardSet.add(currentCrawlerfilestandard);
		}
		return crawlerfilestandardSet;
	}

	@Transactional
	public List<Crawlerfilestandard> findAllCrawlerfilestandards(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Crawlerfilestandard>(
				crawlerfilestandardDAO.findAllCrawlerfilestandards(startResult, maxRows));
	}

	@Transactional
	public Crawlerfilestandard findCrawlerfilestandardByPrimaryKey(Integer id) {
		return crawlerfilestandardDAO.findCrawlerfilestandardByPrimaryKey(id);
	}

	@Transactional
	public Integer countCrawlerfilestandards() {
		return ((Long) crawlerfilestandardDAO.createQuerySingleResult("select count(o) from Crawlerfilestandard o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countCrawlerfilestandards(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Crawlerfilestandard.class);
		return ((Long) crawlerfilestandardDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countCrawlerfilestandardsByName(String queryName) {
		Query query = crawlerfilestandardDAO.createNamedQuery("countCrawlerfilestandardsByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countCrawlerfilestandardsByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Crawlerfilestandard.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadCrawlerfilestandardObjectReferencedSet(Crawlerfilestandard crawlerfilestandard) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> crawlerfilesIds = new HashSet<Integer>();
		for (Crawlerfile obj : crawlerfilestandard.getCrawlerfilesForCrawlerfilestandard()) {

			crawlerfilesIds.add(obj.getId());
		}
		objectReferencedSetMap.put("crawlerfilesIds", crawlerfilesIds);
		Set<Integer> crawlerfilestandardetailsIds = new HashSet<Integer>();
		for (Crawlerfilestandardetail obj : crawlerfilestandard.getCrawlerfilestandardetailsForCrawlerfilestandard()) {

			crawlerfilestandardetailsIds.add(obj.getId());
		}
		objectReferencedSetMap.put("crawlerfilestandardetailsIds", crawlerfilestandardetailsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadCrawlerfilestandardClassReferencedSet(Crawlerfilestandard crawlerfilestandard) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("crawlerfiles", crawlerfileDAO.findAllCrawlerfiles());
		classReferencedSetMap.put("crawlerfilestandardetails",
				crawlerfilestandardetailDAO.findAllCrawlerfilestandardetails());

		return classReferencedSetMap;
	}

	public boolean isEquals(Crawlerfilestandard crawlerfilestandard, Object obj) {
		if (obj == crawlerfilestandard)
			return true;
		if (!(obj instanceof Crawlerfilestandard))
			return false;
		Crawlerfilestandard comparedCrawlerfilestandard = (Crawlerfilestandard) obj;
		if (!CheckPropertyEqual(crawlerfilestandard.getName(), comparedCrawlerfilestandard.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

